package com.example.cardemo.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.cardemo.R
import com.example.cardemo.bean.NewslistBean

class NewsAdapter : RecyclerView.Adapter<NewsAdapter.MyHolder>() {
    private var mDatas: List<NewslistBean.NewslistData> = ArrayList()
    private var itemClickListener: OnItemClickListener? = null

    fun setListData(listData: List<NewslistBean.NewslistData>) {
        this.mDatas = listData
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
        // Load layout file
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_news, parent, false)
        return MyHolder(view)
    }

    override fun getItemCount(): Int {
        return mDatas.size
    }

    override fun onBindViewHolder(holder: MyHolder, position: Int) {
        // Bind data
        val data = mDatas[position]
        holder.author_name.text = "Source: ${data.author_name}"
        holder.date.text = data.date
        holder.title.text = data.title

        // Load image, check if thumbnail_pic_s is null
        val thumbnailUrl = data.thumbnail_pic_s
        if (thumbnailUrl != null) {
            Glide.with(holder.itemView.context)
                .load(thumbnailUrl)
                .into(holder.thumbnail_pic_s)
        } else {
            // If thumbnail_pic_s is null, set a default image
            Glide.with(holder.itemView.context)
                .load(R.drawable.ic_launcher_foreground) // Replace with your default image resource
                .into(holder.thumbnail_pic_s)
        }

        // Click event
        holder.itemView.setOnClickListener {
            itemClickListener?.onItemClick(data, position)
        }
    }

    class MyHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val thumbnail_pic_s: ImageView = itemView.findViewById(R.id.thumbnail_pic_s)
        val title: TextView = itemView.findViewById(R.id.title)
        val author_name: TextView = itemView.findViewById(R.id.author_name)
        val date: TextView = itemView.findViewById(R.id.date)
    }

    interface OnItemClickListener {
        fun onItemClick(data: NewslistBean.NewslistData, position: Int)
    }

    fun setOnItemClickListener(listener: OnItemClickListener) {
        this.itemClickListener = listener
    }
}